package com.party.admin.biz.article;

import com.party.admin.biz.file.FileBizService;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.article.Article;
import com.party.core.model.article.ArticleGroup;
import com.party.core.model.article.ArticleMember;
import com.party.core.model.article.ArticleType;
import com.party.core.model.material.MaterialMember;
import com.party.core.model.serviceguide.ServiceGuideRelation;
import com.party.core.service.article.IArticleGroupService;
import com.party.core.service.article.IArticleMemberService;
import com.party.core.service.article.IArticleService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.material.IMaterialMemberService;
import com.party.core.service.serviceguide.IServiceGuideRelationService;
import com.party.core.utils.MyBeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Arrays;
import java.util.List;

/**
 * 文章业务接口
 * Created by wei.li
 *
 * @date 2017/3/22 0022
 * @time 19:44
 */
@Service
public class ArticleBizService {
    @Autowired
    private IArticleMemberService articleMemberService;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private CosBizService cosBizService;
    @Autowired
    private IArticleGroupService articleGroupService;
    @Autowired
    private IServiceGuideRelationService serviceGuideRelationService;
    @Autowired
    private IMaterialMemberService materialMemberService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 拼接分销连接
     *
     * @param id       活动编号
     * @param memberId 创建者
     * @return 分销连接
     */
    public String getDistributionUrl(String id, String memberId) {
        StringBuilder stringBuilder = new StringBuilder("article/article_distribution_detail.html?");
        stringBuilder.append("id=").append(id)
                .append("&parentId=").append("0")
                .append("&distributorId=").append(memberId);
        return stringBuilder.toString();
    }

    public void uploadQrCode(String memberId, String articleId) throws Exception {
        String filePath = fileBizService.getUploadCIPath(memberId, "article");

        String fileName = "detail_" + articleId;
        String content = "article/article_detail.html?id=" + articleId;
        fileBizService.uploadCloudOut(fileName, filePath, content, memberId);

        String disFileName = "dis_" + articleId;
        String disContent = getDistributionUrl(articleId, memberId);
        fileBizService.uploadCloudOut(disFileName, filePath, disContent, memberId);
    }


    public void saveOrUpdateArticleMember(String articleId, String memberIds) {
        if (StringUtils.isNotEmpty(memberIds)) {
            ArticleMember articleMember = new ArticleMember();
            articleMember.setArticleId(articleId);
            List<ArticleMember> memberList = articleMemberService.list(articleMember);
            for (ArticleMember db : memberList) {
                articleMemberService.deleteByUnique(articleId, db.getMemberId());
            }

            for (int i = 0; i < memberIds.split(",").length; i++) {
                ArticleMember mm = new ArticleMember();
                mm.setArticleId(articleId);
                mm.setMemberId(memberIds.split(",")[i]);
                articleMemberService.insert(mm);
            }
        }
    }

    public void saveOrUpdateMaterialMember(String articleId, String memberIds) {
        if (StringUtils.isNotEmpty(memberIds)) {
            MaterialMember materialMember = new MaterialMember();
            materialMember.setArticleId(articleId);
            List<MaterialMember> memberList = materialMemberService.list(materialMember);
            for (MaterialMember db : memberList) {
                materialMemberService.deleteByUnique(articleId, db.getMemberId());
            }
            for (int i = 0; i < memberIds.split(",").length; i++) {
                MaterialMember insertMaterialMember = new MaterialMember();
                insertMaterialMember.setArticleId(articleId);
                insertMaterialMember.setMemberId(memberIds.split(",")[i]);
                materialMemberService.insert(insertMaterialMember);
            }
        }
    }

    public void deleteArticleMember(String articleId) {
        ArticleMember articleMember = new ArticleMember();
        articleMember.setArticleId(articleId);
        List<ArticleMember> memberList = articleMemberService.list(articleMember);
        for (ArticleMember db : memberList) {
            articleMemberService.deleteByUnique(articleId, db.getMemberId());
        }
    }

    /**
     * 删除文章
     *
     * @param articleId 文章编号
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean deleteArticleBiz(String articleId) {
        boolean endResult = true;
        String memberId = null;
        try {
            if (StringUtils.isEmpty(articleId)) {
                endResult = false;
                return endResult;
            }
            Article article = articleService.get(articleId);
            if (article == null) {
                endResult = false;
                return endResult;
            }
            memberId = article.getMemberId();
            articleMemberService.deleteByArticleId(articleId);
            articleService.delete(articleId);
        } catch (Exception e) {
            endResult = false;
            logger.error("删除文章失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            if (endResult) {
                try {
                    String filePath = fileBizService.getUploadCIPath(memberId, "article");
                    String detailPath = CosBizService.getDeleteQrCodePath(filePath, "detail_" + articleId);
                    cosBizService.deleteFile(detailPath);
                    String distributorPath = CosBizService.getDeleteQrCodePath(filePath, "dis_" + articleId);
                    cosBizService.deleteFile(distributorPath);
                } catch (Exception e) {
                    logger.error("删除文章二维码失败", e);
                }
            }
        }
        return endResult;
    }

    /**
     * 删除文章组
     *
     * @param articleGroupId 文章组编号
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean deleteArticleGroupBiz(String articleGroupId) {
        boolean endResult = true;
        try {
            ArticleGroup articleGroup = articleGroupService.get(articleGroupId);
            if (articleGroup == null) {
                return false;
            }
            List<Article> articles = articleService.getByArticleGroupId(articleGroupId);
            for (Article article : articles) {
                boolean result = this.deleteArticleBiz(article.getId());
                if (!result) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
            }
            articleGroupService.delete(articleGroupId);
        } catch (Exception e) {
            endResult = false;
            logger.error("删除频道失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return endResult;
    }



    public void saveOrupdateArticle(Article article,String members,String memberId) throws Exception{

        if (StringUtils.isNotEmpty(article.getContent())) {
            String content = StringUtils.escapeHtml4Iframe2Video(article.getContent().trim());
            article.setContent(content);
        }

        if (article.getReadNum() == null) {
            article.setReadNum(0);
        }

        if (StringUtils.isNotEmpty(article.getId())) {
            Article t = articleService.get(article.getId());
            MyBeanUtils.copyBeanNotNull2Bean(article, t);// 将编辑表单中的非NULL值覆盖数据库记录中的值
            articleService.update(t);
            memberId = t.getMemberId();
            this.saveOrUpdateArticleMember(t.getId(), members);

            if (article.getIsShowAll().equals(YesNoStatus.YES.getCode())) {
                articleMemberService.deleteByArticleId(article.getId());
            }

            //指南类型
            if (StringUtils.isNotEmpty(article.getCategoryList()) && article.getCategoryList().length() > 0) {

                String categoryids = article.getCategoryList();
                //添加没有的类型
                for (String categoryId : categoryids.split(",")) {
                    List<ServiceGuideRelation> serviceGuideRelationList = serviceGuideRelationService.list(new ServiceGuideRelation(article.getId(),categoryId));
                    if (serviceGuideRelationList.size()==0) {
                        ServiceGuideRelation serviceGuideRelation = new ServiceGuideRelation(article.getId(),categoryId);
                        serviceGuideRelationService.insert(serviceGuideRelation);
                    }
                }
                //删除没有的类型
                List<ServiceGuideRelation> old_SGRList = serviceGuideRelationService.list(new ServiceGuideRelation(article.getId(),null));
                List<String> oldCategories = LangUtils.transform(old_SGRList, input -> input.getSgtId());

                List<String> newCategories = Arrays.asList(categoryids.split(","));
                oldCategories.removeAll(newCategories);


                for (String oldPic : oldCategories) {
                    serviceGuideRelationService.deleteSGR(new ServiceGuideRelation(article.getId(), oldPic));
                }
            }

        } else {
            article.setCreateBy(memberId);
            article.setUpdateBy(memberId);
            article.setMemberId(memberId);
            article.setArticleType(ArticleType.ARTICLE_TYPE_SERVICE.getCode());
            String articleId = articleService.insert(article);
            this.saveOrUpdateArticleMember(articleId, members);


            if (StringUtils.isNotEmpty(article.getCategoryList()) && article.getCategoryList().length() > 0) {
                for (String categoryId : article.getCategoryList().split(",")) {
                    serviceGuideRelationService.insert(new ServiceGuideRelation(articleId, categoryId));
                }
            }
        }

        try {
            this.uploadQrCode(memberId, article.getId());
        } catch (Exception e) {
            logger.error("生成文章二维码异常", e);
        }
    }

    /**
    * @Description:  素材管理保存
    * @Param:
    * @return:
    * @Author: Hua Qunhao
    * @Date: 2019/12/10
    */
    public void materialmgmtSave(Article article,String members,String memberId) throws Exception{
        if (StringUtils.isNotEmpty(article.getContent())) {
            String content = StringUtils.escapeHtml4Iframe2Video(article.getContent().trim());
            article.setContent(content);
        }
        if (article.getReadNum() == null) {
            article.setReadNum(0);
        }
        if (StringUtils.isNotEmpty(article.getId())) {
            Article t = articleService.get(article.getId());
            MyBeanUtils.copyBeanNotNull2Bean(article, t);// 将编辑表单中的非NULL值覆盖数据库记录中的值
            articleService.update(t);
            memberId = t.getMemberId();
            if (article.getIsShowAll().equals(YesNoStatus.YES.getCode())) {
                materialMemberService.deleteByArticleId(article.getId());
            }else{
                this.saveOrUpdateMaterialMember(t.getId(), members);
            }
        } else {
            article.setCreateBy(memberId);
            article.setUpdateBy(memberId);
            article.setMemberId(memberId);
            article.setArticleType(ArticleType.ARTICLE_TYPE_MATERIAL.getCode());
            String articleId = articleService.insert(article);
            this.saveOrUpdateMaterialMember(articleId, members);
        }
        try {
            this.uploadQrCode(memberId, article.getId());
        } catch (Exception e) {
            logger.error("生成文章二维码异常", e);
        }
    }
}
